package clientcore

import (
	"io/ioutil"
	"log"
	"net/http"
	"strings"

	"go.opencensus.io/trace"
)

func (slf *Core) pacHandler(w http.ResponseWriter, r *http.Request) {
	_, span := trace.StartSpan(r.Context(), "pacHandler")
	defer span.End()

	data, err := ioutil.ReadFile(slf.Cfg.PAC)
	log.Printf("GET PAC CONFIG: %v", err)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	rd := strings.Replace(string(data), "__PROXY__", "PROXY "+slf.Cfg.ProxyAddress, -1)
	w.Header().Add("Content-Type", "application/x-ns-proxy-autoconfig")
	w.Write([]byte(rd))
}
